import _thread
import time
import threading
from fundinfo.models import *
from fundinfo.catchdata import *

catchFailsFundInfo = []
fundCodeListToBeCatch = []
fundInfoCatchLock = threading.Lock()

def init():
    funds = FundName.objects.filter(name="").exclude(selfType=1).all()
    for fund in funds:
        fundCodeListToBeCatch.append(fund.code)
    return

def getOneFund():
    code = None
    fundInfoCatchLock.acquire()
    if len(fundCodeListToBeCatch) == 0:
        fundInfoCatchLock.release()
        return None

    code = fundCodeListToBeCatch[0]
    fundCodeListToBeCatch.remove(code)
    fundInfoCatchLock.release()

    funds = FundName.objects.filter(code=code).all()
    if funds == None:
        return None

    return funds[0]

def refreshFundInfo():
    fund = getOneFund()
    if fund == None:
        return False

    try:
        fund.name, fund.type, fund.risk, fund.company = getFundData(fund.code)
        fund.save()
        print("catch fundinfo success,", fund.code, fund.name)
    except:
        print("catch", fund.code, "fail")
        fund.selfType = 1
        fund.save()
        catchFailsFundInfo.append(fund.code)
    
    return True

def refreshFundInfoWorker(name, index):
    print("start thread:", name)
    while True:
        ret = refreshFundInfo()
        if ret == False:
            return
        time.sleep(1)

def StartRefreshFundInfoThreads():
    init()
    for i in range(1,5):
        _thread.start_new_thread(refreshFundInfoWorker, ("fundInfo"+str(i), i))


